package com.tind.tindpracticeapplication.module.scan;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Point;
import android.util.Base64;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.huawei.hms.ml.scan.HmsScan;
import com.tind.tindpracticeapplication.R;
import com.tind.tindpracticeapplication.module.scan.draw.ChildViewAttribute;
import com.tind.tindpracticeapplication.module.scan.draw.ScanResultView;
import com.tind.tindpracticeapplication.module.scan.inter.CommonHandleMessageListener;
import com.tind.tindpracticeapplication.module.scan.inter.ImageViewOnclickListener;
import com.tind.wyf.baselib.base.BaseActivity;
import com.tind.wyf.baselib.dialog.AlertDialogUtils;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Params:
 * @Author :wyf
 * @Date :2023/4/12 11:04
 * @Description :说明 华为scanplus 扫码组件测试界面
 */
public class HuaWeiMultiScanplusActivity extends BaseActivity implements CommonHandleMessageListener, ImageViewOnclickListener {
    private static final int CAMERA_REQ_CODE = 0X001;
    public int REQUEST_CODE_SCAN = 0X012;
    public static final String SCAN_RESULT = "scanResult";
    private SurfaceView mSurfaceView;
    public ScanResultView scanResultView;
    private CameraOperation cameraOperation;
    private SurfaceCallBack surfaceCallBack;
    private SurfaceHolder surfaceHolder;
    private CommonHandler handler;

    private boolean isShow;

    @Override
    protected int getLayoutId() {
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        return R.layout.activity_hua_wei_scanplus;
    }

    @Override
    protected void initView() {
        mSurfaceView = $(R.id.surfaceView);
        scanResultView = $(R.id.scan_result_view);
//        btnStopScan = $(R.id.btn_stop_scan);
    }

    @Override
    protected void initData() {
        cameraOperation = new CameraOperation();
        surfaceCallBack = new SurfaceCallBack();
        surfaceHolder = mSurfaceView.getHolder();
        isShow = false;
        adjustSurface(mSurfaceView);
    }

    private void adjustSurface(SurfaceView cameraPreview) {
        FrameLayout.LayoutParams paramSurface = (FrameLayout.LayoutParams) cameraPreview.getLayoutParams();
        if (getSystemService(Context.WINDOW_SERVICE) != null) {
            ChildViewAttribute childViewAttribute = new ChildViewAttribute();
            WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
            Display defaultDisplay = windowManager.getDefaultDisplay();
            Point outPoint = new Point();
            defaultDisplay.getRealSize(outPoint);
            float sceenWidth = outPoint.x;
            float sceenHeight = outPoint.y;
            float rate;

            if (sceenWidth / (float) CameraOperation.height > sceenHeight / (float) CameraOperation.width) {
                rate = sceenWidth / (float) CameraOperation.height;
                int targetHeight = (int) (CameraOperation.width * rate);
                paramSurface.width = FrameLayout.LayoutParams.MATCH_PARENT;
                paramSurface.height = targetHeight;
                childViewAttribute.sw = sceenWidth;
                childViewAttribute.sh = targetHeight;
                int topMargin = (int) (-(targetHeight - sceenHeight) / 2);
                childViewAttribute.leftM = 0;
                childViewAttribute.topM = topMargin;
                if (topMargin < 0) {
                    paramSurface.topMargin = topMargin;
                }
            } else {
                rate = sceenHeight / (float) CameraOperation.width;
                int targetWidth = (int) (CameraOperation.height * rate);
                paramSurface.width = targetWidth;
                paramSurface.height = FrameLayout.LayoutParams.MATCH_PARENT;
                childViewAttribute.sw = targetWidth;
                childViewAttribute.sh = sceenHeight;
                int leftMargin = (int) (-(targetWidth - sceenWidth) / 2);
                childViewAttribute.leftM = leftMargin;
                childViewAttribute.topM = 0;
                if (leftMargin < 0) {
                    paramSurface.leftMargin = leftMargin;
                }
            }
            scanResultView.setChildViewAttribute(childViewAttribute);
        }
    }

    private void initCamera() {
        try {
            PictureSizeFilter filter = new PictureSizeFilter();
            cameraOperation.setPictureSizeFilter(filter);
            cameraOperation.open(surfaceHolder);
            if (null == handler)
                handler = new CommonHandler(HuaWeiMultiScanplusActivity.this, cameraOperation, 555);
            handler.setCommonHandleMessageListener(this);
        } catch (IOException e) {
            Log.w(TAG, e);
        }
    }

    public void btnBack(View view) {
        this.finish();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isShow) {
            initCamera();
        } else {
            surfaceHolder.addCallback(surfaceCallBack);
        }
    }

    @Override
    protected void onPause() {
        if (handler != null) {
            handler.quit();
            handler = null;
        }
        cameraOperation.close();
        if (!isShow) {
            surfaceHolder.removeCallback(surfaceCallBack);
        }
        super.onPause();
    }

    /**
     * @Params:
     * @Author :wyf
     * @Date :2023/6/21 18:20
     * @Description :说明 对扫码返回的结果 在预览界面进行位置标识
     */
    @Override
    public void hmsScanResult(HmsScan[] hmsScanArr, Bitmap bitmap2) {
        if (null != hmsScanArr) {
            for (int i = 0; i < hmsScanArr.length; i++) {
                scanResultView.add(new ScanResultView.HmsScanGraphic(scanResultView, hmsScanArr[i], Color.GREEN, bitmap2, this));
            }
        }
        scanResultView.setCameraInfo(1080, 1920);
        scanResultView.invalidate();
        if (null != handler)
            handler.sendEmptyMessageDelayed(1, 1000);

    }

    /**
     * @Params:
     * @Author :wyf
     * @Date :2023/6/21 18:15
     * @Description :说明 对二维码 条形码 显示的指示图标进行点击操作
     */
    @Override
    public void scanGraphicOnClick(HmsScan hmsScan) {
//        Log.e(TAG, "点击操作 scanGraphicOnClick: " + hmsScan.getOriginalValue());
//        Toast.makeText(this, "提示：" + hmsScan.getOriginalValue(), Toast.LENGTH_SHORT).show();
        showDialog(hmsScan);
    }

    class SurfaceCallBack implements SurfaceHolder.Callback {

        @Override
        public void surfaceCreated(SurfaceHolder holder) {
            if (!isShow) {
                isShow = true;
                initCamera();
            }
        }

        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

        }

        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {
            isShow = false;
        }
    }

    /**
     * @Params:
     * @Author :wyf
     * @Date :2023/4/24 11:26
     * @Description :说明 扫码结果显示、确认
     */
    private void showDialog(HmsScan data) {
        View view = LayoutInflater.from(this).inflate(R.layout.layout_dialog_message, null);
        view.getBackground().setAlpha(0);
        AlertDialog alertDialog = AlertDialogUtils.getInstance(this)
                .getAlertDialog(HuaWeiMultiScanplusActivity.this, R.style.dialog, view);
//        alertDialog.setView(view, 0, 0, 0, 0);
        TextView content = view.findViewById(R.id.Dlg_content);
        TextView mDlgNo = view.findViewById(R.id.Dlg_No);
        TextView mDlgYes = view.findViewById(R.id.Dlg_Yes);
        content.setText(data.getOriginalValue());
        Log.e("showDialog: ", data.getOriginalValue());
        mDlgYes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("type", "类型");
                intent.putExtra("data", data.getOriginalValue());
//                intent.putExtra("data1", data);
                setResult(RESULT_OK, intent);
                alertDialog.dismiss();
                HuaWeiMultiScanplusActivity.this.finish();
            }
        });
        mDlgNo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
            }
        });
        alertDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        alertDialog.show();
    }

}